/**
 * @date 2006-7-10
 */

package org.nanhill.moo.service.impl;

import java.util.List;

import org.nanhill.commons.model.pagination.Pagination;
import org.nanhill.commons.model.pagination.ThreePartNumberPagination;
import org.nanhill.commons.pattern.search.SearchConstant;
import org.nanhill.commons.pattern.search.SearchException;
import org.nanhill.moo.dao.FavorDao;
import org.nanhill.moo.domain.Favor;
import org.nanhill.moo.domain.query.FavorQuery;
import org.nanhill.moo.service.FavorService;

/**
 * @author alin [xalinx at gmail dot com]
 * @date 2006-7-10
 */
public class FavorServiceImpl extends AbstractService implements FavorService {

	private FavorDao favorDao;

	public void setFavorDao(FavorDao favorDao) {
		this.favorDao = favorDao;
	}

	public void open(Favor favor) {
		this.favorDao.save(favor);

	}

	public Favor loadById(long favorId) {
		return this.favorDao.findById(favorId);
	}

	public void removeById(long favorId) {
		this.favorDao.deleteById(favorId);
	}

	private int checkPageSize(int pageSize) {
		if (pageSize < CONFIG.getFavorMinPageSize()) {
			pageSize = CONFIG.getFavorMinPageSize();
		} else if (pageSize > CONFIG.getFavorMaxPageSize()) {
			pageSize = CONFIG.getFavorMaxPageSize();
		}
		return pageSize;
	}

	public Pagination<Favor> loadPageLatest(int pageId, int pageSize,
			long costId, long userId, long categoryId) throws SearchException {
		pageSize = checkPageSize(pageSize);
		int start = pageSize * (pageId - 1);
		FavorQuery query = new FavorQuery();
		query.setStart(start);
		query.setPageSize(pageSize);
		query.setUserId(userId);
		query.setCategoryId(categoryId);
		query.setCostId(costId);
		query.setFavorIdOrder(SearchConstant.DESC);
		List<Favor> favors = favorDao.findPart(query);
		long count = favorDao.findCount(query);
		ThreePartNumberPagination<Favor> favorPage = new ThreePartNumberPagination<Favor>();
		favorPage.setPages(favors.iterator());
		favorPage.setCount(count);
		favorPage.setPageId(pageId);
		favorPage.setPageSize(pageSize);
		return favorPage;
	}
}
